import { useEffect, useState, useRef } from 'react';
import { Modal, Button } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import loadable from '@loadable/component';
import $ from 'cash-dom';
import dayjs from 'dayjs';

import { GET_FILE_STREAM } from '@/config/url';
import { insertScript } from '@/utils';

import styles from './index.module.scss';

export default props => {
    const initState = () => ({
        loading: true,
        posterData: {},

        posterUrl: '',
    });
    const [state, setState] = useState(initState);
    const { open, onCancel, onOk, posterId='' } = props;
    const { userInfo={} } = useSelector(s => s.common);
    const modelWidth = 360;

    // 获取海报信息
    const getPosterInfo = id => {
        return;
        ({id}).then(res => {
            setState(o => ({...o, loading: false}));
            if(OK_CODE === res?.code) {
                const data = res?.data || {};
                try{
                    const config = JSON.parse(data.config);
                    const obj = {width: modelWidth, height: parseInt(config.height * modelWidth / config.width)};

                    const posterData = {...data, config: {...config, ...obj}};
                    setState(o => ({...o, posterData}));
                    let t = setTimeout(() => {
                        clearTimeout(t);

                        initCanvas(posterData);
                    }, 300);
                }catch(e){}
            }
        }).catch(e => {
            setState(o => ({...o, loading: false}));
        });
    };
    const downloadPoster = () => {
        const canvas = document.getElementById('poster-canvas');
        if (!canvas) return console.error('Canvas not found');

        canvas.toBlob((blob) => {
            if (!blob) {
                alert('生成图片失败，可能存在跨域问题');
                return;
            }

            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `海报_${dayjs().format('YYMMDD')}.png`;

            // 确保链接被添加到DOM
            link.style.display = 'none';
            document.body.appendChild(link);

            // 触发下载
            link.click();

            // 延迟清理，确保下载开始
            let t = setTimeout(() => {
                clearTimeout(t);

                document.body.removeChild(link);
                URL.revokeObjectURL(url);
            }, 100);
        }, 'image/png', 1.0);
    }
    // 将用户头像处理成base64，不然导出时有跨域问题
    const imageToBase64 = (url='') => {
        return new Promise((resolve, reject) => {
            fetch(`${GET_FILE_STREAM}?url=${url}`)
                .then(response => response.blob())
                .then(blob => {
                    let reader = new FileReader();
                    reader.onloadend = function() {
                        resolve(reader.result);
                    };
                    reader.readAsDataURL(blob);
                }).catch(error => {
                    console.error(error);
                    reject();
                });
        });
    };
    // 加载图片，辅助函数
    const loadImage = (image) => {
        return new Promise((resolve, reject) => {
            if(!image) return resolve();

            if(image.complete) {
                return resolve();
            }else{
                image.onload = resolve;
            }
            image.onerror = reject;
        });
    }

    // 初始化画布
    const initCanvas = async (posterData={}) => {
        const canvas = document.getElementById('poster-canvas');
        const ctx = canvas.getContext('2d');
        const { config={}, modelUrl } = posterData || {};
        const { width, height, avatarInfo, nameInfo, qrCodeInfo } = config || {};
        const bgInfo = {url: modelUrl, width, height};
        const invitationUrl = `${location.origin}/?inviter=${userInfo?.invitationCode || ''}`;
        const userName = userInfo?.nickName || '新用户';
        const avatar = (userInfo?.avatar || '').indexOf('/default-avatar') !== -1 ? '' : (userInfo?.avatar || '');
        const canvasScale = 2; // 放大2倍绘制，可以让图片清晰一些

        canvas.width = bgInfo.width*canvasScale;
        canvas.height = bgInfo.height*canvasScale;

        // 生成底图
        let posterBgImage = new Image();
        posterBgImage.src =  await imageToBase64(bgInfo.url);

        let qrCodeImage = null;
        if(true) {
            // 生成二维码
            $('#qrcode').empty();
            let qrcode = new QRCode(document.getElementById("qrcode"), {
                text: invitationUrl,
                width: 96,
                height: 96,
                colorDark : "#000000",
                colorLight : "#ffffff",
                correctLevel : QRCode.CorrectLevel.H
            });
            qrCodeImage = qrcode._oDrawing._elCanvas;
        }

        let avatarImage = null;
        if(true) {
            // 头像转换(兜底的默认头像)
            let avatarBase64 = '/images/default-avatar.svg';
            if(avatar) {
                try{
                    avatarBase64 = await imageToBase64(avatar)
                }catch(e){console.log(e);};
            }
            avatarImage = new Image();
            avatarImage.src = avatarBase64;

        }

        // 头像
        Promise.all([loadImage(posterBgImage), loadImage(avatarImage)]).then(() => {
            // 绘制背景图
            ctx.drawImage(posterBgImage, 0, 0, canvas.width, canvas.height);
            // 绘制圆形头像
            if(avatarImage) {
                ctx.save();
                ctx.beginPath();
                ctx.arc((avatarInfo.left+avatarInfo.width/2)*canvasScale, (avatarInfo.top+avatarInfo.width/2)*canvasScale, (avatarInfo.width/2)*canvasScale, 0, 2*Math.PI);
                ctx.closePath();
                ctx.clip(); // 裁剪为圆形
                ctx.drawImage(avatarImage, avatarInfo.left*canvasScale, avatarInfo.top*canvasScale, avatarInfo.width*canvasScale, avatarInfo.height*canvasScale);
                ctx.restore();
            }
            if(true) {
                // 绘制二维码
                ctx.drawImage(qrCodeImage, qrCodeInfo.left*canvasScale, qrCodeInfo.top*canvasScale, qrCodeInfo.width*canvasScale, qrCodeInfo.height*canvasScale);
            }
            if(true) {
                // 写名字
                ctx.font = `${parseInt(nameInfo.fontSize)*canvasScale}px Arial`;
                ctx.fillStyle = nameInfo.color || 'white';
                ctx.fillText((userName.length > 24 ? `${userName.substring(0, 24)}...` : userName), nameInfo.left*canvasScale, nameInfo.top*canvasScale+parseInt(nameInfo.fontSize)*canvasScale);
            }

            const posterUrl = canvas.toDataURL('image/png');
            setState(o => ({...o, loading: false, posterUrl}));
        }).catch(e => {
            console.log(e?.msg || e?.message || '生成海报失败');
            setState(o => ({...o, loading: false}));
        });
    };

    const afterOpenChange = open => {
        if(open) getPosterInfo(posterId);
    }

    useEffect(() => {
        insertScript('/js/qrcode.min.js');
    }, []);

    return (
        <Modal
            header={null}
            footer={null}
            maskClosable={true}
            closable={false}
            onCancel={onCancel}
            open={open}
            rootClassName={styles['modal-root']}
            width={360}
            afterOpenChange={afterOpenChange}
            loading={state.loading}
            destroyOnHidden={true}
        >
            <div className={styles['container']} id="poster-image">
                <canvas id="poster-canvas"></canvas>
                <div style={{display:'none'}}><div id="qrcode"></div></div>
            </div>

            <div className={styles['image']}>
                <img src={state.posterUrl} alt="" />
            </div>

            <div className={styles['footer']}>
                <Button type="primary" shape="round" onClick={downloadPoster}>下载海报</Button>
            </div>
        </Modal>
    );
}
